
import 'package:courseapp/cache/loadcache.dart';
import 'package:courseapp/entity/loaddto.dart';
import 'package:courseapp/entity/loadquery.dart';
import 'package:courseapp/http/HttpUtils.dart';
import 'package:courseapp/page/teacher/teacherindex.dart';
import 'package:courseapp/utils/custom_appbar.dart';
import 'package:flutter/material.dart';

import 'student/studentindex.dart';

class LoadWidget extends StatefulWidget{

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _LoadState();
  }

}


class _LoadState extends State<LoadWidget> {

   String user;
   String password;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: customAppbar(title: "登陆", borderBottom: false),
      body: Align(alignment: Alignment.center,widthFactor: 1.0,heightFactor: 1.0,
      child: Padding(padding: EdgeInsets.only(left:10,top:20,right:10) ,child:Column(children: <Widget>[
      TextField(decoration: InputDecoration(prefixIcon:Icon(Icons.people), labelText: "账户", hintText: "请输入账户",),onChanged: _saveUser,),
      TextField(decoration: InputDecoration(prefixIcon: Icon(Icons.lock),labelText: "密码", hintText: "请输入密码"),onChanged: _savePassword,obscureText: true,),
      Container(constraints: BoxConstraints(minWidth: double.infinity),
          padding:EdgeInsets.only(top: 20),
          child: FlatButton(color: Colors.blue,
                   highlightColor: Colors.blue[700],
                   colorBrightness: Brightness.dark,
                   splashColor: Colors.grey,
                   child: Text("登录"),
                   shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
                   onPressed: load,)),
      ],))
      )
    );
  }

  load() {
     HttpUtil.getInstance().postLogin(LoadQuery(user:user,password:password)).asStream().listen((LoadDto dto){
        print( "code:" +  dto.msg);
        if(dto.code == 0) {
         showDialog(context: context,builder: _generateAlertDialog);
        }
        if(dto.code == 1) {
          LoadCache.setCache(dto);
          if(dto.data.roleId == 1) {
             Navigator.push(context,new MaterialPageRoute(builder:(context){ return StudentHome();}));
          } else {
            Navigator.push(context,new MaterialPageRoute(builder:(context){ return TeacherIndex();}));
          }
        }

     });
  }






   Widget _generateAlertDialog(BuildContext context) {
     return AlertDialog(
       title: Text('提示'),
       content: Text('用户未找到'),
       actions: <Widget>[
         FlatButton(
           child: Text('确认'),
           onPressed: () {
             Navigator.of(context).pop();
           },
         ),
       ],
     );
   }




  _saveUser(String user) {
   this.user = user;
  }

  _savePassword(String password) {
    this.password = password;
  }


}



